package com.InterestingExercises;

import java.util.Random;

public class 生成验证码1 {
    public static void main(String[] args) {
        String s = generateVerificationCode(6);
        System.out.println("生成的验证码是:\n[ " + s + " ]");
/*
生成的验证码是:
[ b0ZH53OUP7 ]
生成的验证码是:
[ Y76EsQYNhu ]
生成的验证码是:
[ 2KNmUf3Sik ]
生成的验证码是:
[ b7qJRn ]
生成的验证码是:
[ tiKDw4 ]
生成的验证码是:
[ 7WAlpN ]
*/
    }

    /**
     * 生成指定位数的随机验证码,包含数字和字母
     *
     * @param verificationCodeLength
     * @return String
     */
    public static String generateVerificationCode(int verificationCodeLength) {
        Random rd = new Random();
        String verificationCode = "";//空字符串用于连接随机生成的字符
        for (int i = 0; i < verificationCodeLength; i++) {
            int type = rd.nextInt(3);//0,1,2 分别表示数字字符,大写字母,小写字母
            switch (type) {
                case 0://随机一个0-9数字字符
                    verificationCode += rd.nextInt(10);//用+连接字符串
                    break;
                case 1://随机一个A-Z大写字母
                    verificationCode += (char) (rd.nextInt(26) + 'A');
                    break;
                case 2://随机一个a-z小写字母
                    verificationCode += (char) (rd.nextInt(26) + 'a');
                    break;
            }
        }
        return verificationCode;
    }


}
